package com.example.demo.aspect;

import com.example.demo.annotation.ValidateParam;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.Objects;
import java.util.regex.Pattern;

/**
* @Author : liqiang
* @Date : 2020/12/13 9:33
* @Description : 参数切面，校验参数信息
**/
@Aspect
@Component
public class ValidateAspect {

    /**
     * 配置切入点
     * **/
    @Pointcut("@annotation(com.example.demo.annotation.Validate)")
    public void validate(){}

    /**
     * 拦截所有含注解@Validate的方法，考虑到实际业务中可能传对象，可能传单一参数
     * **/
    @Before("validate()")
    public void fieldValidate(JoinPoint joinPoint) throws Throwable{
        System.out.println("开始验证参数");
        //获取方法的请求参数并遍历
        Object[] args = joinPoint.getArgs();
        for (Object arg : args){
            Field[] fields = arg.getClass().getDeclaredFields();
            //遍历所有属性，并针对于有@ValidateParam注解的属性
            for(Field field : fields){
                field.setAccessible(true);
                if(field.isAnnotationPresent(ValidateParam.class)){
                    ValidateParam validateParam = field.getAnnotation(ValidateParam.class);
                    boolean required = validateParam.required();
                    String regular = validateParam.regular();
                    Object fildObj = field.get(arg);
                    System.out.println("param："+String.valueOf(fildObj));
                    if(required){
                        if(Objects.isNull(fildObj)){

                            throw new RuntimeException("前端将 " + field.getName() + " 传了null");
                        }
                    }

                    if (!StringUtils.isEmpty(regular)) {
                        Pattern pattern = Pattern.compile(regular);
                        if (!pattern.matcher(String.valueOf(fildObj)).matches()) {
                            throw new RuntimeException("前端将 " + field.getName() + " 传了不合要求的参数");
                        }
                    }
                }
            }
        }
    }
}
